package com.open.api.ftp.util;

import com.alibaba.fastjson.JSON;
import com.open.api.bo.ImageBO;
import com.open.api.bo.MessageBO;
import com.open.api.util.IDUtils;
import com.open.api.util.MD5Util;
import com.open.api.ftp.common.ResponseData;
import com.open.api.ftp.common.TypeEnum;
import com.open.api.model.ResultModel;
import com.open.api.util.MyImageUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class FileIOUtil_2 {
    /**
     * 写入数据
     */
    public ResultModel saveDataToFile(MessageBO messageBO, String savePath, String fileSuffix) {
        ResultModel resultModel=new ResultModel();
        BufferedWriter writer = null;
        File file_dir=new File(savePath+messageBO.getSystem());
        if(!file_dir.exists()){
            file_dir.mkdirs();
        }
        String fileName=getFileName();
        File file = new File(savePath+messageBO.getSystem()+"/"+messageBO.getSystem()+"_"+messageBO.getResource()+"_"+messageBO.getAction()+"_"+fileName+fileSuffix);
        //如果文件不存在，则新建一个
        if(!file.exists()){
            try {
                boolean b=file.createNewFile();
                if(b){
                    resultModel.setSuccess(true);
                    System.out.println("新建文件成功!");
                }else{
                    System.out.println("新建文件失败："+savePath+messageBO.getFilename()+fileSuffix);
                    resultModel.setSuccess(false);
                    resultModel.setErrorCode("1");
                    resultModel.setErrorMsg("新建文件失败："+savePath+messageBO.getFilename()+fileSuffix);
                    return resultModel;
                }
            } catch (IOException e) {
               // e.printStackTrace();
                System.out.println("新建文件异常："+e.getMessage());
                resultModel.setSuccess(false);
                resultModel.setErrorCode("4");
                resultModel.setErrorMsg("新建文件异常："+e.getMessage());
                return resultModel;
            }
        }

        messageBO.setFilename(savePath+messageBO.getSystem()+"/"+messageBO.getSystem()+"_"+messageBO.getResource()+"_"+messageBO.getAction()+"_"+fileName+fileSuffix);
        System.out.println("新创建文件名："+fileName+"::::pojo.fileName="+messageBO.getFilename());
        messageBO.setMd5(messageBO.getData()!=null?MD5Util.MD5Encode(String.valueOf(messageBO.getData()),"UTF-8"):"");
        System.out.println("写入数据MD5加密："+messageBO.getMd5());
        //写入
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            writer.write(JSON.toJSONString(messageBO));
        } catch (IOException e) {
            System.out.println("写入数据异常："+e.getMessage());
            resultModel.setSuccess(false);
            resultModel.setErrorCode("4");
            resultModel.setErrorMsg("写入数据异常："+e.getMessage());
            return resultModel;
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                System.out.println("写入数据finally异常："+e.getMessage());
                resultModel.setSuccess(false);
                resultModel.setErrorCode("4");
                resultModel.setErrorMsg("写入数据finally异常："+e.getMessage());
                return resultModel;
            }
        }
        System.out.println("文件写入成功！");
        resultModel.setSuccess(true);
        resultModel.setData(messageBO.getSystem()+"_"+messageBO.getResource()+"_"+messageBO.getAction()+"_"+fileName+fileSuffix);
        return resultModel;
    }

    /**
     * 写入图片信息
     * @param imageBO
     * @param savePath
     * @return
     */
    public ResultModel saveImageToFile(ImageBO imageBO, String savePath,String fileSuffix) {
        ResultModel resultModel=new ResultModel();
        BufferedWriter writer = null;
        File file_dir=new File(savePath+imageBO.getSystem());
        if(!file_dir.exists()){
            file_dir.mkdirs();
        }
        String fileName=getFileName();
        File file = new File(savePath+imageBO.getSystem()+"/"+imageBO.getSystem()+"_"+fileName+fileSuffix);
        //如果文件不存在，则新建一个
        if(!file.exists()){
            try {
                boolean b=file.createNewFile();
                if(b){
                    resultModel.setSuccess(true);
                    System.out.println("新建文件成功："+savePath+imageBO.getSystem()+"_"+fileName+fileSuffix);
                }else{
                    System.out.println("新建文件失败："+savePath+imageBO.getSystem()+"_"+fileName+fileSuffix);
                    resultModel.setSuccess(false);
                    resultModel.setErrorCode("1");
                    resultModel.setErrorMsg("新建文件失败："+savePath+imageBO.getSystem()+"_"+fileName+fileSuffix);
                    return resultModel;
                }
            } catch (IOException e) {
               // e.printStackTrace();
                System.out.println("新建文件异常："+e.getMessage());
                resultModel.setSuccess(false);
                resultModel.setErrorCode("4");
                resultModel.setErrorMsg("新建文件异常："+e.getMessage());
                return resultModel;
            }
        }

        imageBO.setFilename(savePath+imageBO.getSystem()+"/"+imageBO.getSystem()+"_"+fileName+fileSuffix);
        System.out.println("新创建文件名："+fileName+"::::pojo.fileName="+imageBO.getFilename());
        imageBO.setMd5((imageBO.getImagestr()!=null&&!imageBO.getImagestr().isEmpty())?MD5Util.MD5Encode(String.valueOf(imageBO.getImagestr()),"UTF-8"):"");
        System.out.println("写入数据MD5加密："+imageBO.getMd5());
        //写入
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            writer.write(JSON.toJSONString(imageBO));
        } catch (IOException e) {
            System.out.println("写入数据异常："+e.getMessage());
            resultModel.setSuccess(false);
            resultModel.setErrorCode("4");
            resultModel.setErrorMsg("写入数据异常："+e.getMessage());
            return resultModel;
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                System.out.println("写入数据finally异常："+e.getMessage());
                resultModel.setSuccess(false);
                resultModel.setErrorCode("4");
                resultModel.setErrorMsg("写入数据finally异常："+e.getMessage());
                return resultModel;
            }
        }
        System.out.println("文件写入成功！");
        resultModel.setSuccess(true);
        resultModel.setData(imageBO.getSystem()+"_"+fileName+fileSuffix);
        return resultModel;
    }

    /**
     * 读取文件
     * @param fileName
     * @param readPath
     * @return
     */
    public ResultModel getDatafromFile(String fileName,String readPath) {

        ResultModel resultModel=new ResultModel();
        String Path=readPath + fileName;
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("读取数据异常："+e.getMessage());
            resultModel.setSuccess(false);
            resultModel.setErrorCode("4");
            resultModel.setErrorMsg("读取数据异常："+e.getMessage());
            return resultModel;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    System.out.println("关闭读取流异常："+e.getMessage());
                    resultModel.setSuccess(false);
                    resultModel.setErrorCode("4");
                    resultModel.setErrorMsg("关闭读取流异常："+e.getMessage());
                    return resultModel;
                }
            }
        }

        MessageBO messageBO=JSON.toJavaObject((JSON) JSON.parse(laststr),MessageBO.class);
        resultModel.setSuccess(true);
        resultModel.setData(messageBO);
        return resultModel;
    }
    /**
     * 根据目录统计文件夹数量及文件数量
     * @param dirstr
     * @return
     */
    //public static Map<String,Object> DirsAndFilesCount(String dirstr){
    public Map<String,Object> DirsAndFilesCount(String dirstr){
        Map<String,Object> map=new HashMap<>();
        if(!(new File(dirstr)).isDirectory()){
            map.put("code",1);
            map.put("msg","目录不存在!--"+dirstr);
            return map;
        }
        File[] list=new File(dirstr).listFiles();

        int fileCount=0,folderCount=0;
        long length=0;
        List dirNameList=new ArrayList();
        List fileNameList=new ArrayList();
        if(list!=null){
            for(File file:list){
                if(file.isFile()){
                    fileCount++;
                    fileNameList.add(file.getName());
                }else{
                    folderCount++;
                    dirNameList.add(file.getName());
                }
            }
        }else{
            map.put("code",1);
            map.put("msg",dirstr+"是空项目或不存在！");
            return map;
        }


        map.put("fileCount",fileCount);
        map.put("fileNameList",fileNameList);
        map.put("folderCount",folderCount);
        map.put("dirNameList",dirNameList);
        map.put("code",0);
        map.put("msg","success");
        return map;
    }


    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    //public static boolean deleteFile(String sPath) {
    public ResponseData deleteFile(String sPath) {
        boolean flag = false;
        ResponseData responseData=new ResponseData();
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if(file.exists()){
            if(file.isFile()){
                if (file.isFile()) {
                    file.delete();
                    responseData.setCode(0);
                    responseData.setMsg("删除成功！");
                    flag=true;
                    responseData.setData(flag);
                }
            }else {
                responseData.setCode(1);
                responseData.setMsg("不是文件！["+sPath+"]");
                flag=false;
                responseData.setData(flag);
            }

        }else {
            responseData.setCode(1);
            responseData.setMsg("文件不存在！["+sPath+"]");
            flag=false;
            responseData.setData(flag);
        }

        return responseData;
    }

    /**
     * 删除目录（文件夹）以及目录下的文件
     * @param   sPath 被删除目录的文件路径
     * @return  目录删除成功返回true，否则返回false
     */
    //public static boolean deleteDirectory(String sPath) {
    public  ResponseData deleteDirectory(String sPath) {
        boolean flag;
        ResponseData responseData=new ResponseData();

        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            responseData.setCode(1);
            responseData.setMsg("文件不存在！或不是目录！["+sPath+"]");
            responseData.setData(false);
            return  responseData;
            // return false;
        }
        flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = (boolean) deleteFile(files[i].getAbsolutePath()).getData();
                if (!flag) {
                    break;
                }
            } //删除子目录
            else {
                flag = (boolean) deleteDirectory(files[i].getAbsolutePath()).getData();
                if (!flag){
                    break;
                }
            }
        }
        if (!flag) {
            responseData.setCode(1);
            responseData.setMsg("fail");
            responseData.setData(false);
            return responseData;
            //  return false;
        }
        //删除当前目录
        if (dirFile.delete()) {
            responseData.setCode(0);
            responseData.setMsg("success");
            responseData.setData(true);
            return responseData;
            // return true;
        } else {
            responseData.setCode(1);
            responseData.setMsg("fail");
            responseData.setData(false);
            return responseData;
            // return false;
        }
    }

    /**
     * 删除文件或文件夹
     * @param filePath
     * @param deleteType
     * @return
     */
    public  ResponseData deleteFromServer(String filePath,Integer deleteType) {
        ResponseData responseData=new ResponseData();
        //删除文件
        if(deleteType== TypeEnum.DELETETYPE_RMFILE.getCode()){
           /* boolean flag= (boolean) deleteFile(filePath).getData();
            if(flag){
                responseData.setCode(0);
                responseData.setMsg("删除文件成功！");
            }else{
                responseData.setCode(1);
                responseData.setMsg("删除文件失败！");
            }*/
            responseData=deleteFile(filePath);
        }else if(deleteType==TypeEnum.DELETETYPE_RMDIR.getCode()){
            //删除文件夹
            /*
            boolean flag=deleteDirectory(filePath);
            if(flag){
                responseData.setCode(0);
                responseData.setMsg("删除文件夹成功！");
            }else{
                responseData.setCode(1);
                responseData.setMsg("删除文件夹失败！");
            }
            */
            responseData=deleteDirectory(filePath);
        }
        return responseData;
    }

    /**
     * 生成文件名
     * @return
     */
    public String getFileName(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date())+"_"+IDUtils.createID();
    }


    /**
     * 写入图片
     */
    public ResultModel saveImage(String imageName, String savePath, String imageStr) {
        ResultModel resultModel=new ResultModel();
        BufferedWriter writer = null;
        File file_dir=new File(savePath);
        if(!file_dir.exists()){
            file_dir.mkdirs();
        }
        File file = new File(savePath+imageName);
        //如果文件不存在，则新建一个
        if(!file.exists()){
            try {
                boolean b=file.createNewFile();
                if(b){
                    resultModel.setSuccess(true);
                    System.out.println("新建文件成功："+savePath+imageName);
                }else{
                    System.out.println("新建文件失败："+savePath+imageName);
                    resultModel.setSuccess(false);
                    resultModel.setErrorCode("1");
                    resultModel.setErrorMsg("新建文件失败："+savePath+imageName);
                    return resultModel;
                }
            } catch (IOException e) {
                // e.printStackTrace();
                System.out.println("新建文件异常："+e.getMessage());
                resultModel.setSuccess(false);
                resultModel.setErrorCode("4");
                resultModel.setErrorMsg("新建文件异常："+e.getMessage());
                return resultModel;
            }
        }

       ResultModel resultModel_image=MyImageUtil.GenerateImage(imageStr,savePath+imageName);
        if(!resultModel_image.isSuccess()){
            return resultModel_image;
        }
        System.out.println("图片写入成功！");
        resultModel.setSuccess(true);
        resultModel.setData(imageName);
        return resultModel;
    }

    public static void main(String[] args) {


        FileIOUtil_2 fileIOUtil =new FileIOUtil_2();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String content="中电科2";

        MessageBO body=new MessageBO();
        body.setSystem("epms");
        body.setResource("place");
        body.setAction("DELETE");
        body.setData(content);
        //body.setActionurl("/place/csxx/delete/{id}");
        body.setActiondesc("场所基本信息备案_场所信息删除");
        body.setMd5(MD5Util.MD5Encode(content,"utf8"));
        //body.setFilename(sdf.format(new Date())+"_"+System.currentTimeMillis());
        body.setFilename(fileIOUtil.getFileName());
       // body.setSavedir("/home/cloud/nettyFtp");
        System.out.println(JSON.toJSON(body));

        ImageBO imageBO=new ImageBO();
       // imageBO.setImagename("55.jpg");
        imageBO.setSystem("epms");
        imageBO.setImagepath("/home/etc/images/");

        String s="";
         ResultModel r_getimage=  MyImageUtil.GetImageStr("F:\\桌面图片\\11.jpg");
        if(r_getimage.isSuccess()){
            s= (String) r_getimage.getData();
        }
         System.out.println(s.length());
        System.out.println(s);
       // MyImageUtil.GenerateImage(s,"H:\\receive\\33.jpg");
        imageBO.setImagestr(s);
        System.out.println(JSON.toJSON(imageBO));

       // ResponseData responseData=writeAndReadUtils.writeXml(body);
        //Map  responseData=writeAndReadUtils.DirsAndFilesCount("H:/test/epms");
       // ResponseData  responseData=writeAndReadUtils.readXmlToObject("H:/test/epms/place_DELETE_2020-05-13_1589342329728.xml");
       // System.out.println("responseData = " + responseData);
      //  System.out.println(UUIDUtils.create());
       // System.out.println(IDUtils.createID());
    }
}
